const db = require('../db/index')
const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')
const config = require('../config')
exports.reguser = (req, res) => {
    const userInfo = req.body
    // if(!userInfo.username || !userInfo.password){
    //     res.cc('用户名或密不能为空')
    // }
    const sqlStr = 'select * from ev_users where username=?'
    db.query(sqlStr, userInfo.username, (err, results)=>{
        if(err){
            return res.cc(err)
        }

        if(results.length > 0){
            return res.cc('用户名已存在！ ')
        }
        userInfo.password = bcrypt.hashSync(userInfo.password, 10)
        const sql = 'insert into ev_users set?'
        db.query(sql, {username: userInfo.username, password: userInfo.password}, (err, results) => {
            if(err) {
                return res.cc(err)
            }
            if(results.affectedRows !==1) return res.cc('注册失败，请稍后再试！')

            res.cc('注册成功', 0)

        })
    })
}

exports.login = (req, res) => {
    const userinfo = req.body
    const sql = 'select * from ev_users where username = ?'
    db.query(sql, userinfo.username, (err, results) => {
        if(err) return res.cc(err)
        if(results.length !== 1) return res.cc('登录失败！')
        const compareResult = bcrypt.compareSync(userinfo.password, results[0].password)
        if(!compareResult) return res.cc('登录密码错误')
        const user = {... results[0], password: '', user_pic: ''}
        const tokenStr = jwt.sign(user, config.jwtSecretKey, {expiresIn: config.expiresIn})
        res.send({
            status: 0,
            message: '登录成功！',
            token: 'Bearer ' + tokenStr
        })
    })
}